<template>
	<view class="wrap">
		<view id="whiteboard" style="width: 100%; height: 300px;"></view>		
		<view class="control">
			<view class="fanye" @click="camera('reduce')"><image src="../../../static/images/course/zuofanye.png"></image></view>
			<view class="fanye" @click="changePage('reduce')"><u-icon name="arrow-left" color="#333333" size="35"></u-icon></view>
			<view class="ye_num">{{pageIndex + 1 }}/{{sceneState_obj.scenes.length}}</view>
			<view class="fanye" @click="changePage('add')"><u-icon name="arrow-right" color="#333333" size="35"></u-icon></view>
			<view class="fanye" @click="camera('add')"><image src="../../../static/images/course/youfanye.png"></image></view>
		</view>
		<view class="left_control" v-if="isShow">
			<view class="control_icon" @click="useTool('arrow')"><image src="../../static/image/jiantou.png"></image></view>
			<view class="control_icon" @click="useTool('pencil')"><image src="../../static/image/bi.png" style="width: 65%;height: 65%;"></image></view>
			<view class="control_icon" @click="useTool('text')"><image src="../../static/image/wenzi.png" style="width: 70%;height: 70%;"></image></view>
			<view class="control_icon" @click="useTool('eraser')"><image src="../../static/image/xiangpicha.png" style="width: 70%;height: 70%;"></image></view>
			<view class="control_icon" @click="openColor(isColor)"><image src="../../static/image/yszz.png" style="width: 70%;height: 70%;"></image></view>
		</view>
		
		<view class="color-board" v-if="isColor">
			<view class="color-title">颜色选择器</view>
			<view class="color-box">
				<view class="color-item" 
					v-for="(i,index) in colorData"
					:key="index"
					@click="changeColor(i.rgb)"
					:style="{background:i.lab}"></view>
			</view>
		</view>
	</view>
</template>

<script>
	var WhiteWebSdk = require("white-web-sdk");
	var audioPlugin = require('@/node_modules/@netless/white-audio-plugin/dist/index.js');
	var videoPlugin = require('@/node_modules/@netless/white-video-plugin/dist/index.js');
	// var videoPlugin2 = require('@/node_modules/@netless/white-video-plugin2/dist/index.js');
	export default {
		props:{
			config:{
				type:Object,
			},
			options:{
				type:Object
			},
			live_obj:{
				type:Object
			},
			whiteboard:{
				type:Boolean,
				default:false
			},
			isShow:{
				type:Boolean,
				default:false
			}
		},
		data(){
			return {
				appId:this.config.appid,
				scriptTagStatus: 0,
				
				roomInterface:{},
				
				sceneState_obj:{
					index:0,
					scenes:[]
				},
				
				pageIndex:0,
				iswrite:false,
				
				url:'',
				Authorization:"Basic OTcxMWE0OTYxZTQ3NDlkNzgxZjdjZTRjZGFmODIyMWY6ZDIxYTViMThmZmQzNDg3MjlkMzAwNWU4MTZhZTQxYTA=",
				
				// applianceName:'',//当前教具名称
				isColor:false,
				colorData:[{
					rgb:'255,0,0',
					lab:'#FF0000'
				},{
					rgb:'255,165,0',
					lab:'#FFA500'
				},{
					rgb:'255,215,0',
					lab:'#FFD700'
				},{
					rgb:'0,255,0',
					lab:'#00FF00'
				},{
					rgb:'0,0,255',
					lab:'#0000FF'
				},{
					rgb:'160,32,240',
					lab:'#A020F0'
				},{
					rgb:'240,255,255',
					lab:'#F0FFFF'
				},{
					rgb:'245,245,245',
					lab:'#F5F5F5'
				},{
					rgb:'190,190,190',
					lab:'#BEBEBE'
				},{
					rgb:'105,105,105',
					lab:'#696969'
				},{
					rgb:'54,54,54',
					lab:'#363636'
				},{
					rgb:'0,0,0',
					lab:'#000000'
				}],
			}
		},
		mounted() {
			this.init()
		},
		methods:{
			init(){
				var _this = this;
				// 获取roomId
				var url = `https://api.agora.io/edu/v1/apps/${this.options.appid}/room/entry`;
				var room_msg = {
					roomUuid:_this.options.room_no,
					roomName:_this.options.section_name,
					userName:_this.options.user_name,
					type: _this.live_obj.type,
					role: _this.live_obj.role,//1:主播 2:学生
					userUuid:_this.options.user_id
				};
				var requestInit = {
				    method: "POST",
				    headers: {
				        "content-type": "application/json",
						"Authorization": _this.Authorization
				    },
					body:JSON.stringify(room_msg)
				};
				window.fetch(url, requestInit).then(function(response) {
				    return response.json();
				}).then(function(json){
					if(json.code==1101006){
						_this.$u.toast('房间已满')
						setTimeout(()=>{
							uni.navigateBack({})
						},1500)
						return
					}
					var roomID = json.data.roomId
					var user_token = json.data.userToken
					var board_url = `https://api.agora.io/edu/v1/apps/${_this.options.appid}/room/${roomID}/board`;
					var room_obj = {
						roomID:roomID,
						user_token:user_token
					}
					_this.$emit('sendRoomId',room_obj)
					_this.getBoardId(board_url,user_token);//获取boardid
				})
			},
			getBoardId(url,user_token){
				var _this = this
				var requestInit = {
				    method: "GET",
				    headers: {
				        "content-type": "application/json",
						"Authorization":_this.Authorization,
						"token":user_token
				    },
				};
				window.fetch(url, requestInit).then(function(response) {
				    return response.json();
				}).then(function(json){
					var boardId = json.data.boardId;
					var boardToken = json.data.boardToken;
					_this.joinRoom(boardId,boardToken)
				})
			},
			//加入房间
			joinRoom(roomUUID, roomToken){
				var that = this;
				const plugins = (0,WhiteWebSdk.createPlugins)({
					 audio: audioPlugin.audioPlugin,
					 video: videoPlugin.videoPlugin
				})
				plugins.setPluginContext("audio",{
					identity: "host",
				})
				plugins.setPluginContext("video",{
					identity: "host",
				})
				
				// const plugins = WhiteWebSdk.createPlugins({ "video": videoPlugin.videoPlugin });
				// var identity = "guest"
				// plugins.setPluginContext("video",{
				// 	identity: identity
				// })
				var whiteWebSdk = new WhiteWebSdk.WhiteWebSdk({
				    appIdentifier: that.config.netless_appid,
					plugins: plugins
				});
				var joinRoomParams = {
				    uuid: roomUUID,
				    roomToken: roomToken,
					disableDeviceInputs:that.whiteboard,
					disableCameraTransform:!that.whiteboard,
				};
				whiteWebSdk.joinRoom(joinRoomParams).then(function(room) {
					console.log(room)
				    // 加入房间成功，获取 room 对象
					that.roomInterface = room; 
					that.sceneState_obj = room.state.sceneState;
					that.pageIndex = that.sceneState_obj.index;
					// that.whiteboard == true ? room.setWritable(true) : room.setWritable(false);
					
					that.whiteboard == true ? room.disableDeviceInputs = false : room.disableDeviceInputs = true;
					that.whiteboard == true ? room.disableCameraTransform = false : room.disableCameraTransform = true;
					that.startListen();//监听
				    room.bindHtmlElement(document.getElementById("whiteboard"));
				}).catch(function(err) {
				    // 加入房间失败
				    console.error(err);
				});
			},
			startListen(){
				var that = this;
				this.roomInterface.callbacks.on("onRoomStateChanged",function(val){
					if(val.hasOwnProperty('sceneState')){
						that.pageIndex = val.sceneState.index
						that.sceneState_obj = val.sceneState
					}
				})
			},
			setBoard(type){
				var that = this;
				that.iswrite = type;
				type == true ? that.roomInterface.setWritable(true) : that.roomInterface.setWritable(false);
				type == true ? that.roomInterface.disableDeviceInputs = false : that.roomInterface.disableDeviceInputs = true;
				// type == true ? that.roomInterface.disableCameraTransform = false : that.roomInterface.disableCameraTransform = true;
			},
			followBoard(type){
				var that = this;
				if(type == true) that.roomInterface.disableOpertation = true;
				type==true ? that.roomInterface.setViewMode("follower") : that.roomInterface.setViewMode("freedom");//设置用户跟随主播视角
				type==true ? that.roomInterface.disableDeviceInputs = true : that.roomInterface.disableDeviceInputs = false;//禁止用户操作
				type==true ? that.roomInterface.disableCameraTransform = true : that.roomInterface.disableCameraTransform = false;//是否禁止用户移动或缩放视角
				type == true ? that.roomInterface.setWritable(true) : that.roomInterface.setWritable(false);
			},
			// 退出白板房间
			handGoBack(){
				this.roomInterface.disconnect();
			},
			// 切页
			camera(type){
				var that = this;
				var contextPath = this.sceneState_obj.contextPath;
				if(this.iswrite==true||this.whiteboard==true){
					if(type=='reduce') {
						this.pageIndex = 0;
						try{
							this.roomInterface.setScenePath(contextPath+this.sceneState_obj.scenes[this.pageIndex].name);
						}catch(e){
							//TODO handle the exception
							this.roomInterface.setScenePath(contextPath+'/'+this.sceneState_obj.scenes[this.pageIndex].name);
						}
					} else if(type=='add') {
						var arr_length = this.sceneState_obj.scenes.length - 1;
						this.pageIndex = arr_length;
						try{
							this.roomInterface.setScenePath(contextPath+this.sceneState_obj.scenes[arr_length].name);
						}catch(e){
							//TODO handle the exception
							this.roomInterface.setScenePath(contextPath+'/'+this.sceneState_obj.scenes[arr_length].name);
						}
					}
				}else{
					that.$u.toast('没有权限')
				}
			},
			//切换页面
			changePage(type){
				var that = this;
				var contextPath = that.sceneState_obj.contextPath;
				if(this.iswrite==true||this.whiteboard==true){
					if(type=='reduce'){
						if(that.pageIndex<1) return
						that.pageIndex -= 1;
						try{
							that.roomInterface.setScenePath(contextPath+that.sceneState_obj.scenes[that.pageIndex].name);
						}catch(e){
							//TODO handle the exception
							that.roomInterface.setScenePath(contextPath+'/'+that.sceneState_obj.scenes[that.pageIndex].name);
						}
					}else if(type=='add'){
						if(that.pageIndex>=that.sceneState_obj.scenes.length-1) return
						that.pageIndex += 1;
						try{
							that.roomInterface.setScenePath(contextPath+that.sceneState_obj.scenes[that.pageIndex].name);
						}catch(e){
							//TODO handle the exception
							that.roomInterface.setScenePath(contextPath+'/'+that.sceneState_obj.scenes[that.pageIndex].name);
						}
					}
				}else{
					that.$u.toast('没有权限')
				}
			},
			useTool(type){
				var that = this;
				that.roomInterface.setMemberState({currentApplianceName:type})
			},
			openColor(type){
				this.isColor = !type
				// var applianceName = this.roomInterface.state.memberState.currentApplianceName;
				// this.applianceName = applianceName
			},
			changeColor(value){
				var yy = []
				var mm = []
				yy = value.split(",")
				for(var i=0;i<yy.length;i++){
					var c = yy[i]
					mm.push(c)
				}
				this.roomInterface.setMemberState({
					strokeColor:mm
				})
				this.isColor = !this.isColor
			}
		}
	}
</script>

<style lang="scss" scoped>
	.wrap{
		position: relative;
		.left_control{
			width: 70rpx;
			position: absolute;
			left: 20rpx;
			z-index: 999;
			top: 40rpx;
			.control_icon{
				height: 70rpx;
				border-radius: 10rpx;
				overflow: hidden;
				margin-bottom: 10rpx;
				width: 70rpx;
				background-color: #9C9C9C;
				display: flex;
				align-items: center;
				justify-content: center;
				image{
					height: 100%;
					width: 100%;
				}
			}
		}
		.color-board{
			height: 200rpx;
			width: 350rpx;
			position: absolute;
			z-index: 999;
			left: 110rpx;
			top: 220rpx;
			// background-color: pink;
			background: #FFFFFF;
			border-radius: 15rpx;
			overflow: hidden;
			border: 1px solid #E8E8E8;
			.color-title{
				height: 60rpx;
				width: 100%;
				font-size: 24rpx;
				line-height: 60rpx;
				border-bottom: 1px solid #E8E8E8;
				text-indent: 20rpx;
				color: #4F4F4F;
				font-weight: bold;
			}
			.color-box{
				height: 110rpx;
				width: 92%;
				overflow: hidden;
				display: flex;
				flex-wrap: wrap;
				margin: 16rpx auto 0;
				justify-content: space-between;
				.color-item{
					height: 42rpx;
					width: 42rpx;
					border-radius: 25rpx;
					margin-right: 5rpx;
					// background-color: pink;
					overflow: hidden;
					border: 2px solid red;
				}
			}
		}
		.left_control :hover{
			background-color: #4F4F4F;
		}
		.control{
			height: 60rpx;
			width: 50%;
			background-color: #f7f7f7;
			border-radius: 15rpx;
			z-index: 999;
			box-shadow: 0 8rpx 24rpx 0rpx rgba(0,0,0,0.5);
			display: flex;
			justify-content: space-between;
			overflow: hidden;
			position: fixed;
			bottom: 20rpx;
			left: 25%;
			.fanye{
				width: 18%;
				height: 100%;
				overflow: hidden;
				display: flex;
				align-items: center;
				justify-content: center;
				image{
					height: 50rpx;
					width: 50rpx;
					display: block;
					margin: 0 auto;
				}
			}
			.ye_num{
				height: 50rpx;
				width: 28%;
				margin-top: 5rpx;
				background-color: #DCDCDC;
				border-radius: 30rpx;
				font-size: 28rpx;
				line-height: 50rpx;
				text-align: center;
			}
		}
	}
</style>
